package com.qyhl.module_practice.brand;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.utils.MJavascriptInterface;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.cache.SpfManager;
import com.qyhl.webtv.commonlib.utils.view.MyWebView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.OnClick;

@Route( path = ARouterPathConstant.PRACTICE_BRAND_DETAIL)
public class PracticeBrandDetailActivity extends BaseActivity {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.web_layout)
    MyWebView webview;

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_brand_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void init() {
        String titleName = getIntent().getStringExtra("title");
        String detail = getIntent().getStringExtra("detail");
        title.setText(titleName);

        showContent(detail);
    }

    @Override
    protected void setListener() {

    }


    @OnClick(R2.id.back_btn)
    public void onViewClicked() {
        finish();
    }

    //展示内容
    private void showContent(String content) {
        initWebView();
        if (StringUtils.isNotEmpty(content)) {
            String htmlString = getNewContent(content);
            webview.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);
            webview.addJavascriptInterface(new MJavascriptInterface(this, StringUtils.returnImageUrlsFromHtml(htmlString)), "imagelistener");
            webview.setWebViewClient(new MyWebViewClient());
        }

    }


    //Web视图
    class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webview.getSettings().setBlockNetworkImage(true);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return false;
            }

            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            /*
             * 非wifi下不加载图片
             */
            if (NetUtil.isWifi(PracticeBrandDetailActivity.this)) {
                webview.getSettings().setBlockNetworkImage(false);
            } else {
                if (SpfManager.getInstance(PracticeBrandDetailActivity.this).getBoolean("noPicture", false)) {
                    webview.getSettings().setBlockNetworkImage(true);
                } else {
                    webview.getSettings().setBlockNetworkImage(false);
                }
            }
            //这个是一定要加上那个的,配合scrollView和WebView的height=wrap_content属性使用
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            //重新测量
            webview.measure(w, h);
            addImageClickListener(view);
        }

        @SuppressLint("JavascriptInterface")
        @JavascriptInterface
        private void addImageClickListener(WebView webView) {
            webView.loadUrl(
                    "javascript:(function(){"
                            + "  var objs = document.getElementsByTagName(\"img\"); "
                            + "  for(var i=0;i<objs.length;i++){"
                            + "     objs[i].onclick=function(){"
                            + "          window.imagelistener.openImage(this.src);  "
                            + "     }"
                            + "  }"
                            + "})()");
        }
    }

    //初始化webview
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDefaultTextEncodingName("utf-8");
        webview.getSettings().setUseWideViewPort(false);
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setBlockNetworkImage(true);
    }

    //webview中的图片自适应大小
    private String getNewContent(String htmltext) {
        Document doc = Jsoup.parse(htmltext);
        Elements elements = doc.getElementsByTag("img");
        for (Element element : elements) {
//            element.attr("max-width", "100%").attr("max-height", "auto");
            element.attr("style", "max-width:100%;height:auto;");
        }
        doc.select("div.titleDivs").remove();
        Log.i("VACK", doc.toString());
        return doc.toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_BRAND_DETAIL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_BRAND_DETAIL);
    }
}
